<template>
  <div class="boookinfolist">
    <el-form
      ref="searchForm"
      :inline="true"
      :model="searchWhere"
      class="demo-form-inline"
    >
      <el-form-item label="书名" prop="bookName">
        <el-input v-model="searchWhere.bookName" placeholder="书名"></el-input>
      </el-form-item>
      <el-form-item label="出版社" prop="press" @click.right.prevent.native="dialogPressVisible=true">
        <el-input v-model="searchWhere.press" placeholder="出版社"> </el-input>
      </el-form-item>
      <el-form-item label="图书类型" prop="bookType">
        <el-select v-model="searchWhere.bookType" placeholder="图书类型">
          <el-option
            v-for="option in bookTypeOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出版日期" prop="publicationdate">
        <el-date-picker
          v-model="searchWhere.publicationdate"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchDate">查询</el-button>
        <el-button @click="resetForm('searchForm')">重置</el-button>
        <el-button type="primary" @click="addHandle">新增</el-button
        >
      </el-form-item>
    </el-form>
    <el-table :data="boookinfolist" style="width: 100%" max-height="550">
      <el-table-column fixed type="index" label="序号" width="80">
      </el-table-column>
      <el-table-column prop="bookISBN" label="书号" width="150">
      </el-table-column>
      <el-table-column prop="bookName" label="书名" width="200">
      </el-table-column>
      <el-table-column prop="author" label="作者" width="120">
      </el-table-column>
      <el-table-column prop="press" label="出版社" width="200">
      </el-table-column>
      <el-table-column prop="publicationdate" label="出版日期" width="150">
      </el-table-column>
      <el-table-column prop="price" label="价格" width="120"> </el-table-column>
      <el-table-column prop="quantity" label="库存数量" width="120">
      </el-table-column>
      <el-table-column prop="bookType" label="图书类型" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.bookType | bookTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row.id)"
            >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          ></template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 新增对话框 -->
    <el-dialog
      title="编辑图书信息"
      :visible.sync="dialogFormVisible"
      width="500px"
      ><el-form
        :model="form"
        label-width="100px"
        ref="addForm"
        label-position="right"
        style="width: 400px; margin-top: -20px"
        :rules="rules"
        ><el-form-item label="书号" prop="bookISBN">
          <el-input v-model="form.bookISBN"></el-input>
        </el-form-item>
        <el-form-item label="书名" prop="bookName">
          <el-input v-model="form.bookName"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="press">
          <el-input v-model="form.press"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="publicationdate">
          <el-date-picker
            v-model="form.publicationdate"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model.number="form.quantity"></el-input>
        </el-form-item>
        <el-form-item label="图书类型" prop="bookType">
          <el-select v-model="form.bookType" placeholder="请选择图书类型">
            <el-option
              v-for="option in bookTypeOptions"
              :key="option.type"
              :label="option.name"
              :value="option.type"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="form.id===null?addData('addForm'):updateData('addForm')">确定</el-button>
      </div>
    </el-dialog>
    <!-- 选择出版社对话框 -->
    <el-dialog title="选择出版社" :visible.sync="dialogPressVisible" width="900px">
      <Press @sendData="getData"></Press>
      </el-dialog>
  </div>
</template>
<script>
import boookinfoApi from "@/api/bookinfo";
import Press from"@/views/press/press.vue";
const bookTypeOptions = [
  { type: "1", name: "编程类" },
  { type: "2", name: "前端类" },
  { type: "3", name: "设计类" },
  { type: "4", name: "移动开发类" },
];
export default {
  components:{
    Press
  },
  data() {
    return {
      dialogFormVisible: false,
      dialogPressVisible:false,
      form: {
        bookISBN:'',
        bookName:'',
        author:'',
        press:'',
        publicationdate:'',
        quantity: 500,//设置初值
        price:0,
        bookType:''
      },
      boookinfolist: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      searchWhere: {
        id:null,
        bookName: "",
        press: "",
        bookType: "",
        publicationdate: "",
      },
      //表单校验规则
      rules: {
        bookISBN: [{ required: true, message: "请输入书号", tirgger: "blur" }],
        bookName: [{ required: true, message: "请输入书名", trigger: "blur" }],
        publicationdate: [
          {
            required: true,
            message: "请选择日期",
            trigger:["blur", "change"]
          },
        ],
        quantity: [
          { required: true, message: "数量不能为空",trigger: "blur"},
          { type: "number", message: "数量必须为数字", trigger: "blur" },
        ],
      },
      bookTypeOptions,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  filters: {
    bookTypeFilter(type) {
      const booktypeobj = bookTypeOptions.find((obj) => obj.type === type);
      return booktypeobj ? booktypeobj.name : null;
    },
  },
  created() {
    this.fetchDate();
  },
  methods: {
    getData(currentRow){
      this.searchWhere.press=currentRow.pressName
      this.searchWhere.id=currentRow.id
      this.dialogPressVisible=false
    },
    updateData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          boookinfoApi.updateBook(this.form).then(response=>{
            const resp=response.data
            if(resp.flag){
              this.fetchDate()
              this.form.id=null
              this.dialogFormVisible=false
            }
            else{
              this.$message({
                message:resp.message,
                type:'warning'
              })
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addHandle(){
      this.dialogFormVisible=true
      this.$nextTick(()=>{
        this.$refs['addForm'].resetFields()
      })  
    },
    fetchDate() {
      // boookinfoApi.getBookInfoList().then((response) => {
      boookinfoApi
        .search(this.currentPage, this.pageSize, this.searchWhere)
        .then((response) => {
          const resp = response.data;
          console.log(resp.data.rows);
          this.boookinfolist = resp.data.rows;
          this.total = resp.data.total;
        });
    },
    handleEdit(id) {
      console.log(id);
      this.addHandle();
      boookinfoApi.getBookById(id).then(response=>{
        const resp=response.data
        if(resp.flag){
          this.form=resp.data
        }else{
          this.$message({
            message:resp.message,
            type:'warning'
          }) 
        }
      })
    },
    handleDelete(id) {
      console.log('id');
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          boookinfoApi.deleteBookById(id).then(response=>{
            const resp=response.data
             this.$message({
            type: resp.flag?'success':'error',
            message:response.message
          })
          if(resp.flag){
            this.fetchDate()
          }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      console.log(`每页${size}条`);
      this.fetchDate();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      console.log(`当前页：${currentPage}`);
      this.fetchDate();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          boookinfoApi.add(this.form).then(response=>{
            const resp=response.data
            if(resp.flag){
              this.fetchDate()
              this.dialogFormVisible=false
            }
            else{
              this.$message({
                message:resp.message,
                type:'warning'
              })
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除弹窗
    open() {
        this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
  }
};
</script>
<style scoped>
</style>
